package mamikeji.liaowa.ui.activity.forum;

import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.umeng.analytics.MobclickAgent;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import mamikeji.liaowa.R;
import mamikeji.liaowa.bean.MyForumBean;
import mamikeji.liaowa.bean.Web_Focus;
import mamikeji.liaowa.bean.Web_Praise;
import mamikeji.liaowa.bean.Web_forum_changeBean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.BaseActivity;
import mamikeji.liaowa.ui.activity.circle.PreviewCircleImgActivity;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MultiStateView;


public class ForumMSGActivity extends BaseActivity {
    private static final String TAG = "ForumMSGActivity";
    @BindView(R.id.webView_forum_msg)
    WebView webViewForumMsg;
    @BindView(R.id.progressBar_forum_msg)
    ProgressBar progressBarForumMsg;
    @BindView(R.id.multiStateView_my_topic_details)
    MultiStateView multiStateViewMy_Topic_Details;
    private MyForumBean.DataEntity dataEntity;
    boolean bool_forum_refresh = false;
    private Web_forum_changeBean web_forum_changeBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forum_msg);
        ButterKnife.bind(this);
        //无网络
        ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        if (info == null || !manager.getBackgroundDataSetting()) {
            multiStateViewMy_Topic_Details.setViewState(MultiStateView.VIEW_STATE_NOINTERNET);
        } else {
            multiStateViewMy_Topic_Details.setViewState(MultiStateView.VIEW_STATE_CONTENT);
        }

        getBase();
        setTitleLeftImage(R.drawable.icon_fanhuibai_n_fff, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (webViewForumMsg.canGoBack()) {
                    webViewForumMsg.goBack();
                } else {
                    if (bool_forum_refresh) {
                        Intent intent = new Intent();
                        intent.putExtra("web_forum_changeBean", web_forum_changeBean);
                        setResult(RESULT_OK, intent);
                    }
                    finish();
                }
            }
        });
        web_forum_changeBean = new Web_forum_changeBean(0, 0, 0, new ArrayList<Web_Focus>(), 0);
        dataEntity = (MyForumBean.DataEntity) getIntent().getSerializableExtra("MyForumBean");
        if (dataEntity.getCertification() == null) {
            setTitleName(dataEntity.getNickname());
        } else {
            setTitleName(dataEntity.getCertification().equals("") ?
                    dataEntity.getNickname() :
                    dataEntity.getNickname() + "(" + dataEntity.getCertification() + ")");
        }
        setTitleRightBtn(dataEntity.getIs_collection() == 1 ?
                R.string.forum_msg_right_sel : R.string.forum_msg_right_null, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initCollectionDate();
            }
        });

        multiStateViewMy_Topic_Details.getView(MultiStateView.VIEW_STATE_ERROR).findViewById(R.id.button_error_refish)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        multiStateViewMy_Topic_Details.setViewState(MultiStateView.VIEW_STATE_LOADING);
                        initLoadUrl();
                    }
                });


        //初始化WebView的配置
        initConfiguration();
        //加载页面
        initLoadUrl();
        //设置js调用方法
        initListener();
    }

    private void initListener() {
        webViewForumMsg.addJavascriptInterface(new Call() {
            //点击回复或点赞
            @Override
            @JavascriptInterface
            public void clickReplyOrThumb(String response) {
                Web_Praise web_praise = new Gson().fromJson(response, Web_Praise.class);
                web_forum_changeBean.setZanStatic(web_praise.getBoolThumb());
                web_forum_changeBean.setZanNum(Integer.parseInt(web_praise.getThumbNum()));
                web_forum_changeBean.setCommentNum(Integer.parseInt(web_praise.getCommentsNum()));
                bool_forum_refresh = true;

            }

            //显示图片
            @Override
            @JavascriptInterface
            public void displayImages(String response) {
                Web_image_yrl web_image_yrl = new Gson().fromJson(response, Web_image_yrl.class);
                String[] split2 = dataEntity.getTopic_image().split(",");
                ArrayList<String> stringList = new ArrayList<String>();
                int index = 0;
                for (int i = 0; i < split2.length; i++) {
                    if (split2[i].equals(web_image_yrl.getImageurl())) {
                        index = i;
                    }
                    stringList.add(split2[i]);
                }

                Intent intent = new Intent(ForumMSGActivity.this, PreviewCircleImgActivity.class);
                intent.putStringArrayListExtra("urlList", stringList);
                intent.putExtra("position", index);
                ForumMSGActivity.this.startActivity(intent);
            }

            //点击关注
            @Override
            @JavascriptInterface
            public void clickFocus(String response) {
                Web_Focus webFocus = new Gson().fromJson(response, Web_Focus.class);
                web_forum_changeBean.getWebFocusList().add(webFocus);
                ForLog.i("web_forum_changeBean", "" + web_forum_changeBean.getWebFocusList().size());
                bool_forum_refresh = true;

            }

            @Override
            @JavascriptInterface
            public void hideFavorites(String str) {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        TextView textView = setTitleRightBtn(R.string.forum_msg_right_0, null);
                        if (textView != null) {
                            textView.setVisibility(View.GONE);
                        }
                    }
                });
            }
        }, "Android");
    }

    private void initLoadUrl() {
        webViewForumMsg.loadUrl(HttpApi.ROOT_PATH + HttpApi.FORUM_DATE +
                "?usercode=" + ForPreference.getString(ForContents.USER_CODE) +
                "&topic_id=" + dataEntity.getTopic_id());
    }

    private void initConfiguration() {
        WebSettings webSetting = webViewForumMsg.getSettings();
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSetting.setJavaScriptEnabled(true);
        //设置自适应屏幕，两者合用
        webSetting.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSetting.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        //setAllowFileAccess 启用或禁止WebView访问文件数据
        webSetting.setAllowFileAccess(true);
        //setLayoutAlgorithm 设置布局方式
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        //setSupportZoom 设置是否支持变焦
        webSetting.setSupportZoom(true);
        //setBuiltInZoomControls 设置是否支持缩放
        webSetting.setBuiltInZoomControls(true);
        //打开页面时 自适应屏幕
        webSetting.setUseWideViewPort(true);
        //是否支持多窗口
        webSetting.setSupportMultipleWindows(false);

        webSetting.setLoadWithOverviewMode(true);

        webSetting.setAppCacheEnabled(true);

        webSetting.setDatabaseEnabled(true);

        webSetting.setDomStorageEnabled(true);

        webSetting.setJavaScriptEnabled(true);

        webSetting.setGeolocationEnabled(true);

        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);

        webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());

        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());

        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0).getPath());

        //设置缓冲的模式
        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().sync();
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webViewForumMsg.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边
                view.loadUrl(url);
                return true;
            }
        });

        webViewForumMsg.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    progressBarForumMsg.setVisibility(View.GONE);//加载完网页进度条消失

                } else {
                    progressBarForumMsg.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    progressBarForumMsg.setProgress(newProgress);//设置进度值
                }
            }

        });
    }

    /**
     * 收藏文章
     */
    private void initCollectionDate() {
        MobclickAgent.onEvent(this, "HotTopicCollection");//热门话题-收藏
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put("usercode", ForPreference.getString(ForContents.USER_CODE));
        formMap.put("topic_id", dataEntity.getTopic_id() + "");

        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.SendTopicCollection, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
            }

            @Override
            public void onResponse(String response) {
                ForLog.e(TAG, response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        bool_forum_refresh = true;
                        int num = ForPreference.getInt(ForContents.USER_COLLECTION);
                        if (dataEntity.getIs_collection() == 1) {
                            dataEntity.setIs_collection(0);
                            ForPreference.putInt(ForContents.USER_COLLECTION, --num);
                            ForToast.showToast(R.string.collection_delete);
                            web_forum_changeBean.setIsCollection(0);
                        } else {
                            dataEntity.setIs_collection(1);
                            ForPreference.putInt(ForContents.USER_COLLECTION, ++num);
                            ForToast.showToast(R.string.collection_success);
                            web_forum_changeBean.setIsCollection(1);
                        }

                        setTitleRightBtn(dataEntity.getIs_collection() == 1 ?
                                R.string.forum_msg_right_sel : R.string.forum_msg_right_null, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                initCollectionDate();
                            }
                        });
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        webViewForumMsg.onPause();
        MobclickAgent.onPageEnd("热门话题");
    }

    @Override
    protected void onDestroy() {
        //销毁WebView防止泄漏
        if (webViewForumMsg != null) {
            webViewForumMsg.setVisibility(View.GONE);
            webViewForumMsg.removeAllViews();
            webViewForumMsg.destroy();
            webViewForumMsg = null;
        }
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        webViewForumMsg.onResume();
        MobclickAgent.onPageStart("热门话题");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webViewForumMsg.canGoBack()) {
            setTitleRightBtn(dataEntity.getIs_collection() == 1 ?
                    R.string.forum_msg_right_sel : R.string.forum_msg_right_null, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    initCollectionDate();
                }
            });
            webViewForumMsg.goBack();// 返回前一个页面
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (bool_forum_refresh) {
                Intent intent = new Intent();
                intent.putExtra("web_forum_changeBean", web_forum_changeBean);
                setResult(RESULT_OK, intent);
            }
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    private interface Call {
        //点击回复或点赞
        void clickReplyOrThumb(String str);

        //显示图片
        void displayImages(String str);

        //点击关注
        void clickFocus(String str);

        //收藏
        void hideFavorites(String str);
    }

    class Web_image_yrl {
        private String imageurl;
        private String imglist;

        public void setImageurl(String imageurl) {
            this.imageurl = imageurl;
        }

        public void setImglist(String imglist) {
            this.imglist = imglist;
        }

        public String getImageurl() {
            return imageurl;
        }

        public String getImglist() {
            return imglist;
        }
    }

    class Web_right {
        private int BoolhideFavorites;

        public void setBoolhideFavorites(int BoolhideFavorites) {
            this.BoolhideFavorites = BoolhideFavorites;
        }

        public int getBoolhideFavorites() {
            return BoolhideFavorites;
        }
    }
    // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
    // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
    // webSetting.setPreFectch(true);
    // long time = System.currentTimeMillis();
    // TbsLog.d("time-cost", "cost time: "+ (System.currentTimeMillis() - time));
    // webViewForumMsg.setHorizontalScrollBarEnabled(false);//水平不显示
    // webViewForumMsg.setVerticalScrollBarEnabled(false); //垂直不显示

    //老方法
    //webViewForumMsg.addJavascriptInterface(new JsApi(), "Android");
    //webViewForumMsg.setJavascriptInterface(new JsApi());
    //webViewForumMsg.addJavascriptInterface(new JsApi(), "Android");

   /* class JsApi {
        //点击关注
        @JavascriptInterface
        public void clickFocus(JSONObject jsonObject) throws JSONException {
            String response = jsonObject.getString("msg");
            Web_Focus webFocus = new Gson().fromJson(response, Web_Focus.class);
            web_forum_changeBean.getWebFocusList().add(webFocus);
            ForLog.i("web_forum_changeBean", "" + web_forum_changeBean.getWebFocusList().size());
            bool_forum_refresh = true;
        }

        //点击回复或点赞
        @JavascriptInterface
        public void clickReplyOrThumb(String str) throws JSONException {

//            String response = jsonObject.getString("msg");
//            Web_Praise web_praise = new Gson().fromJson(response, Web_Praise.class);
//            web_forum_changeBean.setZanStatic(web_praise.getBoolThumb());
//            web_forum_changeBean.setZanNum(Integer.parseInt(web_praise.getThumbNum()));
//            web_forum_changeBean.setCommentNum(Integer.parseInt(web_praise.getCommentsNum()));
//            bool_forum_refresh = true;

            JSONObject jsonObject = new JSONObject(str);
            String boolThumb = jsonObject.getString("BoolThumb");
            String thumbNum = jsonObject.getString("ThumbNum ");

//            ForLog.i("看看是否点击了", boolThumb);
//            ForLog.i("看看是否点击了", thumbNum);
            System.out.println("boolThumb" + "thumbNum" + boolThumb + thumbNum);

        }

        //显示图片
        @JavascriptInterface
        public void displayImages(JSONObject jsonObject) throws JSONException {
            String response = jsonObject.getString("msg");
            Web_image_yrl web_image_yrl = new Gson().fromJson(response, Web_image_yrl.class);
            String[] split2 = dataEntity.getTopic_image().split(",");
            ArrayList<String> stringList = new ArrayList<String>();
            int index = 0;
            for (int i = 0; i < split2.length; i++) {
                if (split2[i].equals(web_image_yrl.getImageurl())) {
                    index = i;
                }
                stringList.add(split2[i]);
            }

            Intent intent = new Intent(ForumMSGActivity.this, PreviewCircleImgActivity.class);
            intent.putStringArrayListExtra("urlList", stringList);
            intent.putExtra("position", index);
            ForumMSGActivity.this.startActivity(intent);
        }

        //右上角收藏按钮显示状态
        @JavascriptInterface
        public void hideFavorites(JSONObject jsonObject) throws JSONException {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    TextView textView = setTitleRightBtn(R.string.forum_msg_right_0, null);
                    if (textView != null) {
                        textView.setVisibility(View.GONE);
                    }
                }
            });
        }
    }*/
}
